# -*- coding: UTF-8 -*-
# sys.path.append(r"D:\Python\油井措施经济评价\project_code")
import datetime
import os
import re
import shutil
import socket
import sys
# import time
# from pprint import pformat

# sys.path.append(r"F:\03-个人\02-机主\研究生\实验室\油井措施分析\项目\project")
# import schedule
# import uvicorn
# from fastapi.responses import StreamingResponse
import uvicorn
# from starlette.staticfiles import StaticFiles
# sys.path.append(r"/home/project/")
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from backend.app.app.api.data_management.data_management import data_management
from backend.app.app.api.api_v1 import router_v1
from backend.app.app.api.manage_projects import router_project
from backend.app.app.api.calculation import router_e_calculation
from backend.app.app.api.effect_pridict import router_pridict
from backend.app.app.api.api_Hu.api.stim_caculation import router_stim_calculation
from backend.app.app.api.api_Xiong import router_X
from backend.app.app.api.api_save import router_save
from backend.app.app.db.base import load_config
# from backend.app.app.crud_pub.authentication import Authentication
import logging

app = FastAPI(docs_url=None)

# app.mount('/static', StaticFiles(directory='static'))
app.include_router(router_save)
app.include_router(data_management)

app.include_router(router_X)
app.include_router(router_pridict)
app.include_router(router_v1)

app.include_router(router_project)
app.include_router(router_e_calculation)
app.include_router(router_stim_calculation)

# origins = [
#     # "http://localhost.tiangolo.com",
#     "http://47.96.235.182:8885",
#     "http://127.0.0.1:8885",
#     "http://127.0.0.1:8889",
# ]

app.add_middleware(  # 添加中间件
    CORSMiddleware,  # CORS中间件类
    # allow_origins=origins,  # 允许起源
    allow_origins=["*"],  # 允许起源
    allow_credentials=True,  # 允许凭据
    allow_methods=["*"],  # 允许方法
    allow_headers=["*"],  # 允许头部
)


def change_front_ip():
    file_path = "../front/assets/Net.txt"
    # file_path = "E:\\LocalServer\\project\\front\\assets\\Net.txt"
    with open(file_path, 'r', encoding='utf8') as fp:
        config = fp.read()
    pattern = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
    # print(re.findall(pattern, config))
    host_ip = socket.gethostbyname(socket.gethostname())
    config = re.sub(pattern, host_ip, config, re.S)
    with open(file_path, "w", encoding='utf8') as fp:
        fp.write(config)
    # print(config)


def create_file(path, file_type=1):
    """
    创建文件
    @param path: 文件路径
    @param file_type: 文件类型 0:file, 1: dir
    @return:
    """
    if not os.path.exists(path):
        if file_type == 0:
            file = open(path, "w")
            file.close()
        if file_type == 1:
            os.mkdir(path)


def manage_log_file():
    """
    管理日志文件，后端日志保存一个月
    @return:
    """
    create_file("./logs")
    # 获取本月时间和上月时间
    now = datetime.datetime.now()
    this_month = now.month
    last_month = this_month - 1
    if this_month == 1:
        last_month = 12
    this_day = now.day
    # 删除上月日志
    if os.path.exists("./logs/{}".format(last_month)):
        shutil.rmtree("./logs/{}".format(last_month))
    # 存放每个月份的日志目录名
    logs_dir_name = "./logs/{}".format(this_month)
    create_file(logs_dir_name)
    log_file_name = "{}/{}.log".format(logs_dir_name, now.day)
    create_file(log_file_name, 0)
    return log_file_name


# 项目启动时开启日志监听事件
@app.on_event("startup")
async def startup_event():
    change_front_ip()
    logger = logging.getLogger("uvicorn.access")
    handler = logging.handlers.RotatingFileHandler(manage_log_file(), mode="a", maxBytes=100 * 1024, backupCount=3)
    handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
    logger.addHandler(handler)


# #  返回图片
# @app.post("/downloadfile2/", name="测试图片")
# async def download_files_stream():
#     file_like = open('picture/test.jpg', mode="rb")
#     return StreamingResponse(file_like, media_type="image/jpg")
#
#
# @app.get("/")
# async def hello():
#     return {"hello": "world"}

if __name__ == '__main__':
    # config = load_config("./db/config.json")['config']
    config = load_config("./db/config.json")['config']
    input_args = sys.argv
    # print("args", input_args)
    if len(input_args) == 1:
        print("校验未通过！！！")
    else:
        if input_args[1] == "40c7bc25c943b9e8977636aafe5d69e9":
            uvicorn.run(app=app, host="0.0.0.0", port=int(config.get("server_port", 8889)), reload=False, lifespan="on")
        else:
            print("校验未通过！！！")



